/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain (a) copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package io.sentry.ohos.core;

import io.sentry.Breadcrumb;
import io.sentry.IHub;
import io.sentry.Integration;
import io.sentry.SentryLevel;
import io.sentry.SentryOptions;
import io.sentry.ohos.core.util.DeviceOrientations;
import io.sentry.protocol.Device;
import io.sentry.util.Objects;

import ohos.app.Context;
import ohos.app.ElementsCallback;
import ohos.global.configuration.Configuration;

import org.jetbrains.annotations.NotNull;

import java.io.Closeable;
import java.io.IOException;
import java.util.Locale;

/**
 * AppComponentsBreadcrumbsIntegration
 *
 * @since 2021-06-01
 */
public final class AppComponentsBreadcrumbsIntegration
    implements Integration, Closeable, ElementsCallback {
    private static final int TRIM_MEMORY_BACKGROUND = 40;
    private final @NotNull Context context;
    private IHub hub;
    private SentryOhosOptions sentryOhosOptions;

    /**
     * AppComponentsBreadcrumbsIntegration
     *
     * @param context Context
     */
    public AppComponentsBreadcrumbsIntegration(final @NotNull Context context) {
        this.context = Objects.requireNonNull(context, "Context is required");
    }

    @Override
    public void register(final @NotNull IHub ihub, final @NotNull SentryOptions options) {
        this.hub = Objects.requireNonNull(ihub, "Hub is required");
        this.sentryOhosOptions =
            Objects.requireNonNull(
                (options instanceof SentryOhosOptions) ? (SentryOhosOptions) options : null,
                "SentryOhosOptions is required");

        this.sentryOhosOptions
            .getLogger()
            .log(
                SentryLevel.DEBUG,
                "AppComponentsBreadcrumbsIntegration enabled: %s",
                this.sentryOhosOptions.isEnableAppComponentBreadcrumbs());

        if (this.sentryOhosOptions.isEnableAppComponentBreadcrumbs()) {
            try {
                // if its (a) ContextImpl, registerComponentCallbacks can't be used
                options
                    .getLogger()
                    .log(SentryLevel.DEBUG, "AppComponentsBreadcrumbsIntegration installed.");
            } catch (Exception e) {
                this.sentryOhosOptions.setEnableAppComponentBreadcrumbs(false);
                options.getLogger().log(SentryLevel.INFO, e, "ComponentCallbacks2 is not available.");
            }
        }
    }

    @Override
    public void close() throws IOException {
        if (sentryOhosOptions != null) {
            sentryOhosOptions.getLogger().log(SentryLevel.DEBUG, "AppComponentsBreadcrumbsIntegration removed.");
        }
    }

    private void createLowMemoryBreadcrumb(final Integer level) {
        if (hub != null) {
            final Breadcrumb breadcrumb = new Breadcrumb();
            if (level != null) {
                // only add breadcrumb if TRIM_MEMORY_BACKGROUND, TRIM_MEMORY_MODERATE or
                // TRIM_MEMORY_COMPLETE.
                // Release as much memory as the process can.

                // TRIM_MEMORY_UI_HIDDEN, TRIM_MEMORY_RUNNING_MODERATE, TRIM_MEMORY_RUNNING_LOW and
                // TRIM_MEMORY_RUNNING_CRITICAL.
                // Release any memory that your app doesn't need to run.
                // So they are still not so critical at the point of killing the process.

                if (level < TRIM_MEMORY_BACKGROUND) {
                    return;
                }
                breadcrumb.setData("level", level);
            }

            breadcrumb.setType("system");
            breadcrumb.setCategory("device.event");
            breadcrumb.setMessage("Low memory");
            breadcrumb.setData("action", "LOW_MEMORY");
            breadcrumb.setLevel(SentryLevel.WARNING);
            hub.addBreadcrumb(breadcrumb);
        }
    }

    @Override
    public void onMemoryLevel(int level) {
        createLowMemoryBreadcrumb(level);
    }

    @SuppressWarnings("deprecation")
    @Override
    public void onConfigurationUpdated(Configuration configuration) {
        if (hub != null) {
            final Device.DeviceOrientation deviceOrientation =
                DeviceOrientations.getOrientation(context.getResourceManager().getConfiguration().direction);
            String orientation;
            if (deviceOrientation != null) {
                orientation = deviceOrientation.name().toLowerCase(Locale.ROOT);
            } else {
                orientation = "undefined";
            }

            final Breadcrumb breadcrumb = new Breadcrumb();
            breadcrumb.setType("navigation");
            breadcrumb.setCategory("device.orientation");
            breadcrumb.setData("position", orientation);
            breadcrumb.setLevel(SentryLevel.INFO);
            hub.addBreadcrumb(breadcrumb);
        }
    }
}
